package cn.like.log;


import cn.like.log.aspect.SysLogAspect;
import cn.like.log.event.SysLogListener;
import cn.like.log.service.LogService;
import cn.like.log.service.impl.DefaultLogService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.Objects;

/**
 * 日志自动配置
 * <p>
 * 启动条件：
 * 1，存在web环境
 * 2，配置文件中like.log.enabled=true
 * 3，配置文件中不存在：like.log.enabled 值
 * <p>
 * 使用sysLog：
 * 1.请实现 LogService 接口
 */
@EnableAsync
@Configuration
@AllArgsConstructor
@ConditionalOnWebApplication
@ConditionalOnProperty(name = "like.log.enabled", havingValue = "true", matchIfMissing = true)
public class LogAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public SysLogAspect sysLogAspect() {
		return new SysLogAspect();
	}

	@Bean
	@ConditionalOnMissingBean
	public SysLogListener sysLogListener(@Autowired(required = false) LogService logService) {
		if (Objects.isNull(logService))
			logService = DefaultLogService.instance;
		return new SysLogListener(logService::saveLog);
	}
}
